//
//  FMColorPickerController.m
//  FreeMark
//
//  Created by gaopr on 2019/2/17.
//  Copyright © 2019年 gaopr. All rights reserved.
//

#import "FMColorPickerController.h"
#import "HRColorPickerView.h"
#import "HRColorMapView.h"
#import "HRBrightnessSlider.h"

@implementation FMColorPickerController
{
//    id <HRColorPickerViewControllerDelegate> __weak delegate;
    HRColorPickerView *colorPickerView;
    UIColor *_color;
}

- (instancetype)initWithColor:(UIColor *)defaultColor
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _color = defaultColor;
    }
    return self;
}

- (void)setColor:(UIColor *)color
{
    colorPickerView.color = color;
}

- (UIColor *)color
{
    return colorPickerView.color;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!_color)
    {
        _color = [UIColor whiteColor];
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    colorPickerView = [[HRColorPickerView alloc] init];
    colorPickerView.color = _color;
    
    HRColorMapView *colorMapView = [[HRColorMapView alloc] init];
    colorMapView.saturationUpperLimit = @1;
    colorMapView.tileSize = @1;
    [colorPickerView addSubview:colorMapView];
    colorPickerView.colorMapView = colorMapView;
    
    HRBrightnessSlider *slider = [[HRBrightnessSlider alloc] init];
    slider.brightnessLowerLimit = @0;
    [colorPickerView addSubview:slider];
    colorPickerView.brightnessSlider = slider;
    
    [self.view addSubview:colorPickerView];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(onCancel)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(onComfirm)];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    colorPickerView.frame = (CGRect) {.origin = CGPointZero, .size = self.view.frame.size};
    
    if ([self respondsToSelector:@selector(topLayoutGuide)]) {
        CGRect frame = colorPickerView.frame;
        frame.origin.y = self.topLayoutGuide.length;
        frame.size.height -= self.topLayoutGuide.length;
        colorPickerView.frame = frame;
    }

    CGFloat margin = 10;
    CGRect frame = colorPickerView.frame;
    frame.origin.x = margin;
    frame.size.width = self.view.bounds.size.width - 2 * margin;
    colorPickerView.frame = frame;
}

- (void)onCancel
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onComfirm
{
    if ([self.delegate respondsToSelector:@selector(colorPickerControllerOnComfirm:)])
    {
        [self.delegate colorPickerControllerOnComfirm:self];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
